{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "\n",
    "前三节我们使用与房价预测相同的简单神经网络解决手写数字识别问题，效果并不理想，原因有两点：\n",
    "1. 输入数据类型不同。房价预测的输入为离散一维数据。房价预测使用全连接神经网络无法学习到图像二维数据中的空间信息。\n",
    "2. 模型复杂度不够。因为手写数字识别任务涉及到图像信号，比房价预测任务更加复杂，模型的复杂度也会影响最终的效果，理论上复杂的模型能够表示更复杂的转换关系（从输入到输出）。\n",
    "\n",
    "\n",
    "本节介绍两种常见的网络结构，全连接神经网络和卷积神经网络，观测卷积网络能否提升手写数字识别的训练效果。\n",
    "\n",
    "在开始介绍网络结构前，复用上一节的数据处理代码，代码如下。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#数据处理部分之前的代码，保持不变\n",
    "import os\n",
    "import random\n",
    "import paddle\n",
    "import paddle.fluid as fluid\n",
    "from paddle.fluid.dygraph.nn import Conv2D, Pool2D, FC\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from PIL import Image\n",
    "\n",
    "import gzip\n",
    "import json\n",
    "\n",
    "# 定义数据集读取器\n",
    "def load_data(mode='train'):\n",
    "\n",
    "    # 数据文件\n",
    "    datafile = './work/mnist.json.gz'\n",
    "    print('loading mnist dataset from {} ......'.format(datafile))\n",
    "    data = json.load(gzip.open(datafile))\n",
    "    train_set, val_set, eval_set = data\n",
    "\n",
    "    # 数据集相关参数，图片高度IMG_ROWS, 图片宽度IMG_COLS\n",
    "    IMG_ROWS = 28\n",
    "    IMG_COLS = 28\n",
    "\n",
    "    if mode == 'train':\n",
    "        imgs = train_set[0]\n",
    "        labels = train_set[1]\n",
    "    elif mode == 'valid':\n",
    "        imgs = val_set[0]\n",
    "        labels = val_set[1]\n",
    "    elif mode == 'eval':\n",
    "        imgs = eval_set[0]\n",
    "        labels = eval_set[1]\n",
    "\n",
    "    imgs_length = len(imgs)\n",
    "\n",
    "    assert len(imgs) == len(labels), \\\n",
    "          \"length of train_imgs({}) should be the same as train_labels({})\".format(\n",
    "                  len(imgs), len(labels))\n",
    "\n",
    "    index_list = list(range(imgs_length))\n",
    "\n",
    "    # 读入数据时用到的batchsize\n",
    "    BATCHSIZE = 100\n",
    "\n",
    "    # 定义数据生成器\n",
    "    def data_generator():\n",
    "        if mode == 'train':\n",
    "            random.shuffle(index_list)\n",
    "        imgs_list = []\n",
    "        labels_list = []\n",
    "        for i in index_list:\n",
    "            img = np.reshape(imgs[i], [1, IMG_ROWS, IMG_COLS]).astype('float32')\n",
    "            label = np.reshape(labels[i], [1]).astype('float32')\n",
    "            imgs_list.append(img) \n",
    "            labels_list.append(label)\n",
    "            if len(imgs_list) == BATCHSIZE:\n",
    "                yield np.array(imgs_list), np.array(labels_list)\n",
    "                imgs_list = []\n",
    "                labels_list = []\n",
    "\n",
    "        # 如果剩余数据的数目小于BATCHSIZE，\n",
    "        # 则剩余数据一起构成一个大小为len(imgs_list)的mini-batch\n",
    "        if len(imgs_list) > 0:\n",
    "            yield np.array(imgs_list), np.array(labels_list)\n",
    "\n",
    "    return data_generator"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 1. 经典全连接神经网络\n",
    "\n",
    "\n",
    "经典的全连接神经网络含有四层网络：两个隐含层，输入层和输出层。\n",
    "- 输入层。准备数据，输入给神经网络。\n",
    "- 隐含层。增加网络深度和复杂度，隐含层的节点数是可以调整的。节点数越多，神经网络表示能力越强，但同时参数量也会增加。\n",
    "- 输出层。输出网络计算结果，输出层的节点数是固定的，比如手写数字识别有0-9十个数字，输出标签有10个，所以输出层必须是10个节点。\n",
    "\n",
    "------\n",
    "**说明：**\n",
    "\n",
    "隐含层引入非线性激活函数sigmoid是为了增加神经网络的非线性能力，举例来说，一个神经网络有四个输入x1~x4，一个输出y，采用线性变换。假设第一层的变换是z1=x1-x2和z2=x3+x4，第二层的变换是y=z1+z2。将两层的变换展开后得到 y=x1-x2+x3+x4。原始输入和最终输出之间依然是线性关系，无论中间累积了多少层线性变换均是如此。\n",
    "\n",
    "------\n",
    "\n",
    "Sigmoid的函数曲线如下图所示，是早期神经网络模型中常见的非线性变换函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXcAAAD8CAYAAACMwORRAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMi4zLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvIxREBQAAH8lJREFUeJzt3Xl4XPV59vHvM6PNkmzZsrxgS7ZsY2xsMBhkY3DCEggYkpi0IWBICJAUSt6QkpbQF5qWpLR9m6VNmrZOAyUkJSyOIaS44BRwgJAQvIONV5A3LV4kb/KidWae948ZO0KxrcEe6cyM7s916Zoz5xzN3JjRraOz/I65OyIikl1CQQcQEZHUU7mLiGQhlbuISBZSuYuIZCGVu4hIFlK5i4hkIZW7iEgWUrmLiGQhlbuISBbKCeqNy8rKvLKyMqi3FxHJSCtWrNjt7kO6Wy+wcq+srGT58uVBvb2ISEYys23JrKfdMiIiWUjlLiKShVTuIiJZSOUuIpKFVO4iIlmo23I3s0fNrMHM1hxnuZnZv5pZtZmtNrPzUh9TREQ+iGS23H8CzDrB8quB8YmvO4D/OPVYIiJyKro9z93dXzezyhOsci3wmMfv17fYzAaa2WnuviNFGUVEPjB3py0Soz0ao60jRkf091/tEScSi9ERdaIxJxKNEYklpmNONPb75zF3ojGIHZl2J+a/fx7z+HvF3HEnvixx+9JYzHE4uswTua44cxjnVAzs0f/+VFzENBKo7fS8LjHvD8rdzO4gvnXPqFGjUvDWIpJN2iJR9jd3sK+5nX2HO2hq6eBAawcHWyMcaOngUFuE5vYIh9qiHE5M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z9uWZvZY8T37wE8TS//KdhNti8CzybKfKmZxYiPHdEYVC4zO5v4h2iVmUF8t8dKM5vu7jt7OteJsh1hZrcCHwcuD/gevMncFD4QZpZLvNifcPdng87TyUxgtpldAxQAA8zscXf/bMC5IP6XV527H/kr5xni5R60K4At7t4IYGbPAhcBKSn3TN4tsx24JDH9EeC9ALN09d/AZQBmdgaQR8ADFrn7O+4+1N0r3b2S+Af+vN4q9u6Y2Szif9LPdvfmgOMkc1P4Xmfx38o/Ata7+3eDztOZu9/v7uWJz9Yc4JU0KXYSn/FaM5uQmHU5sC7ASEfUADPMrDDx//ZyUnigN6233LtxO/D9xIGIVuCOgPN09ijwqJmtAdqBWwLeEs0E/w7kAy8n/rJY7O53BhHkeDeFDyJLFzOBm4F3zOztxLy/StzjWE7sy8ATiV/Wm4HbAs5DYhfRM8BK4rsi3yKFV6rqClURkSyUybtlRETkOFTuIiJZSOUuIpKFVO4iIllI5S4ikoVU7iIiWUjlLiKShVTuIiJZ6P8DtkRmteUBWjsAAAAASUVORK5CYII=\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "def sigmoid(x):\n",
    "    # 直接返回sigmoid函数\n",
    "    return 1. / (1. + np.exp(-x))\n",
    " \n",
    "# param:起点，终点，间距\n",
    "x = np.arange(-8, 8, 0.2)\n",
    "y = sigmoid(x)\n",
    "plt.plot(x, y)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "\n",
    "下述代码为经典全连接神经网络的实现。完成网络结构定义后，即可训练神经网络。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 多层全连接神经网络实现\n",
    "class MNIST(fluid.dygraph.Layer):\n",
    "    def __init__(self, name_scope):\n",
    "        super(MNIST, self).__init__(name_scope)\n",
    "        name_scope = self.full_name()\n",
    "        # 定义两层全连接隐含层，输出维度是10，激活函数为sigmoid\n",
    "        self.fc1 = FC(name_scope, size=10, act='sigmoid') # 隐含层节点为10，可根据任务调整\n",
    "        self.fc2 = FC(name_scope, size=10, act='sigmoid')\n",
    "        # 定义一层全连接输出层，输出维度是1，不使用激活函数\n",
    "        self.fc3 = FC(name_scope, size=1, act=None)\n",
    "    \n",
    "    # 定义网络的前向计算\n",
    "    def forward(self, inputs, label=None):\n",
    "        outputs1 = self.fc1(inputs)\n",
    "        outputs2 = self.fc2(outputs1)\n",
    "        outputs_final = self.fc3(outputs2)\n",
    "        return outputs_final"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "loading mnist dataset from ./work/mnist.json.gz ......\n",
      "epoch: 0, batch: 0, loss is: [32.990723]\n",
      "epoch: 0, batch: 200, loss is: [8.430781]\n",
      "epoch: 0, batch: 400, loss is: [9.899996]\n",
      "epoch: 1, batch: 0, loss is: [8.9326315]\n",
      "epoch: 1, batch: 200, loss is: [8.640866]\n",
      "epoch: 1, batch: 400, loss is: [8.800435]\n",
      "epoch: 2, batch: 0, loss is: [8.900871]\n",
      "epoch: 2, batch: 200, loss is: [8.005327]\n",
      "epoch: 2, batch: 400, loss is: [7.391898]\n",
      "epoch: 3, batch: 0, loss is: [6.8396983]\n",
      "epoch: 3, batch: 200, loss is: [7.8882074]\n",
      "epoch: 3, batch: 400, loss is: [7.417461]\n",
      "epoch: 4, batch: 0, loss is: [6.296938]\n",
      "epoch: 4, batch: 200, loss is: [6.1883593]\n",
      "epoch: 4, batch: 400, loss is: [6.5852118]\n"
     ]
    }
   ],
   "source": [
    "#网络结构部分之后的代码，保持不变\n",
    "with fluid.dygraph.guard():\n",
    "    model = MNIST(\"mnist\")\n",
    "    model.train()\n",
    "    #调用加载数据的函数，获得MNIST训练数据集\n",
    "    train_loader = load_data('train')\n",
    "    # 使用SGD优化器，learning_rate设置为0.01\n",
    "    optimizer = fluid.optimizer.SGDOptimizer(learning_rate=0.01)\n",
    "    # 训练5轮\n",
    "    EPOCH_NUM = 5\n",
    "    for epoch_id in range(EPOCH_NUM):\n",
    "        for batch_id, data in enumerate(train_loader()):\n",
    "            #准备数据\n",
    "            image_data, label_data = data\n",
    "            image = fluid.dygraph.to_variable(image_data)\n",
    "            label = fluid.dygraph.to_variable(label_data)\n",
    "            \n",
    "            #前向计算的过程\n",
    "            predict = model(image)\n",
    "            \n",
    "            #计算损失，取一个批次样本损失的平均值\n",
    "            loss = fluid.layers.square_error_cost(predict, label)\n",
    "            avg_loss = fluid.layers.mean(loss)\n",
    "            \n",
    "            #每训练了200批次的数据，打印下当前Loss的情况\n",
    "            if batch_id % 200 == 0:\n",
    "                print(\"epoch: {}, batch: {}, loss is: {}\".format(epoch_id, batch_id, avg_loss.numpy()))\n",
    "            \n",
    "            #后向传播，更新参数的过程\n",
    "            avg_loss.backward()\n",
    "            optimizer.minimize(avg_loss)\n",
    "            model.clear_gradients()\n",
    "\n",
    "    #保存模型参数\n",
    "    fluid.save_dygraph(model.state_dict(), 'mnist')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 2.卷积神经网络\n",
    "\n",
    "虽然使用经典的神经网络可以达到一定的准确率，但对于计算机视觉问题，效果最好的模型是卷积神经网络。卷积神经网络针对视觉问题的特点优化了网络结构，更适合处理视觉问题。卷积神经网络的原理会在第四章详述，在这里只展示如何将模型替换成卷积神经网络，以及它带来的效果提升。\n",
    "\n",
    "卷积神经网络由多个卷积层和池化层组合而成，卷积层负责对输入进行扫描以生成更抽象的特征表示，而池化层则对这些特征表示进行过滤，保留最关键的信息。下面是卷积神经网络的实现，卷积和池化函数会在第四章详述，这里仅理解成一种比经典神经网络更强大的模型即可。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 多层卷积神经网络实现\n",
    "class MNIST(fluid.dygraph.Layer):\n",
    "     def __init__(self, name_scope):\n",
    "         super(MNIST, self).__init__(name_scope)\n",
    "         name_scope = self.full_name()\n",
    "         # 定义卷积层，输出特征通道num_filters设置为20，卷积核的大小filter_size为5，卷积步长stride=1，padding=2\n",
    "         # 激活函数使用relu\n",
    "         self.conv1 = Conv2D(name_scope, num_filters=20, filter_size=5, stride=1, padding=2, act='relu')\n",
    "         # 定义池化层，池化核pool_size=2，池化步长为2，选择最大池化方式\n",
    "         self.pool1 = Pool2D(name_scope, pool_size=2, pool_stride=2, pool_type='max')\n",
    "         # 定义卷积层，输出特征通道num_filters设置为20，卷积核的大小filter_size为5，卷积步长stride=1，padding=2\n",
    "         self.conv2 = Conv2D(name_scope, num_filters=20, filter_size=5, stride=1, padding=2, act='relu')\n",
    "         # 定义池化层，池化核pool_size=2，池化步长为2，选择最大池化方式\n",
    "         self.pool2 = Pool2D(name_scope, pool_size=2, pool_stride=2, pool_type='max')\n",
    "         # 定义一层全连接层，输出维度是1，不使用激活函数\n",
    "         self.fc = FC(name_scope, size=1, act=None)\n",
    "         \n",
    "    # 定义网络前向计算过程，卷积后紧接着使用池化层，最后使用全连接层计算最终输出\n",
    "     def forward(self, inputs):\n",
    "         x = self.conv1(inputs)\n",
    "         x = self.pool1(x)\n",
    "         x = self.conv2(x)\n",
    "         x = self.pool2(x)\n",
    "         x = self.fc(x)\n",
    "         return x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "\n",
    "接下来训练定义好的卷积神经网络，比较两个模型的损失变化（经典神经网络和卷积神经网络），可以发现卷积神经网络的损失值下降更快，且最终的损失值更小。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "loading mnist dataset from ./work/mnist.json.gz ......\n",
      "epoch: 0, batch: 0, loss is: [23.737549]\n",
      "epoch: 0, batch: 200, loss is: [4.6651053]\n",
      "epoch: 0, batch: 400, loss is: [4.042445]\n",
      "epoch: 1, batch: 0, loss is: [4.210341]\n",
      "epoch: 1, batch: 200, loss is: [2.9507055]\n",
      "epoch: 1, batch: 400, loss is: [3.4136646]\n",
      "epoch: 2, batch: 0, loss is: [3.1289194]\n",
      "epoch: 2, batch: 200, loss is: [3.2356896]\n",
      "epoch: 2, batch: 400, loss is: [2.4643185]\n",
      "epoch: 3, batch: 0, loss is: [2.3309803]\n",
      "epoch: 3, batch: 200, loss is: [2.6524985]\n",
      "epoch: 3, batch: 400, loss is: [2.4528985]\n",
      "epoch: 4, batch: 0, loss is: [2.2842317]\n",
      "epoch: 4, batch: 200, loss is: [3.308255]\n",
      "epoch: 4, batch: 400, loss is: [2.6887434]\n"
     ]
    }
   ],
   "source": [
    "#网络结构部分之后的代码，保持不变\n",
    "with fluid.dygraph.guard():\n",
    "    model = MNIST(\"mnist\")\n",
    "    model.train()\n",
    "    #调用加载数据的函数\n",
    "    train_loader = load_data('train')\n",
    "    optimizer = fluid.optimizer.SGDOptimizer(learning_rate=0.01)\n",
    "    EPOCH_NUM = 5\n",
    "    for epoch_id in range(EPOCH_NUM):\n",
    "        for batch_id, data in enumerate(train_loader()):\n",
    "            #准备数据\n",
    "            image_data, label_data = data\n",
    "            image = fluid.dygraph.to_variable(image_data)\n",
    "            label = fluid.dygraph.to_variable(label_data)\n",
    "             \n",
    "            #前向计算的过程\n",
    "            predict = model(image)\n",
    "            \n",
    "            #计算损失，取一个批次样本损失的平均值\n",
    "            loss = fluid.layers.square_error_cost(predict, label)\n",
    "            avg_loss = fluid.layers.mean(loss)\n",
    "            \n",
    "            #每训练了100批次的数据，打印下当前Loss的情况\n",
    "            if batch_id % 200 == 0:\n",
    "                print(\"epoch: {}, batch: {}, loss is: {}\".format(epoch_id, batch_id, avg_loss.numpy()))\n",
    "            \n",
    "            #后向传播，更新参数的过程\n",
    "            avg_loss.backward()\n",
    "            optimizer.minimize(avg_loss)\n",
    "            model.clear_gradients()\n",
    "\n",
    "    #保存模型参数\n",
    "    fluid.save_dygraph(model.state_dict(), 'mnist')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "PaddlePaddle 1.6.0 (Python 3.5)",
   "language": "python",
   "name": "py35-paddle1.2.0"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
